package com.github.hxl.upload.demo.util;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 单文件上传工具类
 * 
 * @author shizi
 */
public class FileUploadUtil {

	/**
	 * 较小文件上传方法，单个上传文件
	 * 
	 * @param request
	 * @param desPath 上传文件存放目录
	 * @param fileName 如果为""或者null，则默认以原来的文件名保存
	 * @return 上传后文件名及目录(如果上传失败，则返回 fail)
	 * @throws Exception
	 * @throws Exception
	 */
	public static String upload(HttpServletRequest request, String desPath, String fileName) throws Exception {
		String name = "";
		String path = "fail";

		File tempFile = new File(System.getProperty("java.io.tmpdir"));
		DiskFileItemFactory dfif = new DiskFileItemFactory();
		dfif.setSizeThreshold(4096);
		dfif.setRepository(tempFile);

		ServletFileUpload sfu = new ServletFileUpload(dfif);
		sfu.setFileSizeMax(4194304);

		List items = sfu.parseRequest(request);
		Iterator it = items.iterator();
		while (it.hasNext()) {
			FileItem item = (FileItem) it.next();
			if (!item.isFormField()) {
				name = item.getName();
				int index = name.lastIndexOf("\\");
				if (index > 0) {
					name = name.substring(index + 1);
				}
				if (fileName == null || "".equals(fileName)) {
					File file = new File(desPath, name);
					item.write(file);
					path = file.getAbsolutePath();
				} else {
					File file = new File(desPath, fileName);
					item.write(file);
					path = file.getAbsolutePath();
				}
			}
		}
		return path;
	}
}
